<template>
  <div class="div1">
    <h5>简易图书管理</h5>
    <p>
      <label
        >id:
        <input type="text" placeholder="请输入序号" v-model="id" required />
      </label>

      <label
        >图书名称:
        <input
          type="text"
          placeholder="请输入图书名称"
          v-model="bookname"
          required
        />
      </label>
      <label
        >出版社:
        <input
          type="text"
          placeholder="请输入出版社"
          v-model="press"
          required
        />
      </label>
      <label
        >作者:
        <input type="text" placeholder="请输入作者" v-model="author" required />
      </label>
      <button @click="add">添加</button><br />
    </p>
    <p>
      <label
        >请输入搜索关键字:
        <input type="text" placeholder="请输入搜索关键字" v-model="keyword" />
      </label>
      <button @click="search(keyword)">搜索</button>
    </p>
    <table border="1">
      <thead>
        <tr v-bind:class="trClass">
          <th>序号</th>
          <th>图书名称</th>
          <th>出版社</th>
          <th>作者</th>
          <th>时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-show="show">
        <tr
          v-for="item in search(keyword)"
          :ref="item.id"
          :key="item.id"
          v-bind:class="trClass"
        >
          <td v-if="!isEditing(item.id)" v-text="item.id"></td>
          <td v-if="isEditing(item.id)">
            <input type="text" v-model="item.id" required />
          </td>

          <td v-if="!isEditing(item.id)" v-text="item.bookname"></td>
          <td v-if="isEditing(item.id)">
            <input
              type="text"
              v-model="editFormData[item.id].bookname"
              required
            />
          </td>
          <td v-if="!isEditing(item.id)" v-text="item.press"></td>
          <td v-if="isEditing(item.id)">
            <input type="text" v-model="item.press" required />
          </td>
          <td v-if="!isEditing(item.id)" v-text="item.author"></td>
          <td v-if="isEditing(item.id)">
            <input type="text" v-model="item.author" required />
          </td>
          <td>{{ item.ptime | dateFormat }}</td>

          <td v-if="!isEditing(item.id)">
            <a
              href="#"
              class="btn-success"
              @click.prevent="editBook(item.id)"
              >{{ item.operation[0] }}</a
            >
            <a
              href="#"
              class="btn-success"
              @click.prevent="deleteBook(item.id)"
              >{{ item.operation[1] }}</a
            >
          </td>
          <td v-if="isEditing(item.id)">
            <a href="#" class="btn-success" @click.prevent="saveBook(item.id)"
              >保存</a
            >
            <a href="#" class="btn-success" @click.prevent="cancelEdit(item.id)"
              >取消</a
            >
          </td>
        </tr>
      </tbody>
    </table>

    <h1 v-show="!show">请添加图书</h1>
  </div>
</template>

<script>
export default {
  name: "BooksView",
  data() {
    return {
      trClass: "tr1",
      keyword: "",
      id: "",
      bookname: "",
      press: "",
      author: "",
      editingId: null,
      show: true,
      editFormData: {}, // 用于存储正在编辑的书籍信息
      bookLists: [
        {
          id: 1,
          bookname: "Web前端开发技术",
          press: "清华大学出版社",
          author: "储久良",
          ptime: new Date(),
          operation: ["编辑", "删除"],
        },
        {
          id: 2,
          bookname: "Java程序设计",
          press: "电子工业出版社",
          author: "耿祥义",
          ptime: new Date(),
          operation: ["编辑", "删除"],
        },
        {
          id: 3,
          bookname: "JavaScript高级程序设计",
          press: "高等教育出版社",
          author: "张路路",
          ptime: new Date(),
          operation: ["编辑", "删除"],
        },
      ],
    };
  },
  methods: {
    Metadata({ id, bookname, press, author }) {
      this.bookLists.push({
        id: id,
        bookname: bookname,
        press: press,
        author: author,
        ptime: new Date(),

        operation: ["编辑", "删除"],
      });
    },

    add() {
      // 数据完整性检查
      if (
        this.id != "" &&
        this.bookname != "" &&
        this.press != "" &&
        this.author != ""
      ) {
        // ID唯一性检查：修正逻辑，确保ID未被使用
        const isIdExist = Boolean(
          this.bookLists.find((item) => item.id === this.id)
        );
        if (!isIdExist) {
          // 如果ID不存在于列表中，则添加新书
          this.bookLists.push({
            id: this.id,
            bookname: this.bookname,
            press: this.press,
            author: this.author,
            ptime: new Date(),
            operation: ["编辑", "删除"],
          });
        } else {
          alert("ID已存在，请使用不同的ID！");
        }
      } else {
        alert("图书数据不完整！请补充！");
      }
    },
    deleteBook(i) {
      this.bookLists = this.bookLists.filter((item) => item.id !== i);

      // this.bookLists.splice(i, 1);
    },

    isEditing(id) {
      // console.log(this.editingId === id)
      return this.editingId === id;
    },

    editBook(id) {
      this.editingId = id;

      this.editFormData[id] = {
        ...this.bookLists.find((book) => book.id === id),
      };
      // console.log(this.editFormData)
    },

    saveBook(id) {
      const editedBook = this.editFormData[id];
      console.log("saveBook", editedBook);

      const index = this.bookLists.indexOf((book) => book.id === id);
      if (index !== -1) {
        // 使用解构赋值和扩展运算符合并原始数据和编辑后的数据
        this.bookLists[index] = { ...this.bookLists[index], ...editedBook };
        console.log("bookLists", this.bookLists[index]);
      }

      this.search();
      this.cancelEdit();
    },
    cancelEdit() {
      this.editingId = null;
      this.editFormData = {};
    },

    search(bname) {
      //返回满足条件的图书数组
      var arrBooks = [];
      this.bookLists.forEach((item, i) => {
        if (item.bookname.indexOf(bname) != -1) {
          arrBooks.push(item); //当bname="",indexOf(bname)=0,原数组自动push进来。
        }
      });

      return arrBooks;
    },
  },
  watch: {
    bookLists: {
      handler(newVal) {
        console.log("打印新值", newVal);

        if (newVal == 0) {
          console.log(newVal);
          this.show = false;
        }
      },
      deep: true, // 开启深度监听
    },
  },
};
</script>

<style scoped>
/* 定义图层的样式   */
.div1 {
  margin: 0 auto;
  width: 950px;
  border: 1px dashed #55ed89;
}
/* 设置表格样式 */
table {
  border: 1px solid #42b983;
  text-align: center;
  width: 950px;
  border-collapse: collapse;
}
/* 定义表格表头样式 */
th {
  background: #abb983;
}
/* 定义表格行的样式 */
.tr1 {
  height: 50px;
  padding: 5px auto;
}

tr:nth-child(2n-1) {
  background-color: #a786a5;
}
/*定义h5标记样式 */
h5 {
  text-align: center;
  color: #0033cc;
  padding: 15px;
  background: #afafaf;
  font-size: 28px;
  height: 58px;
}
/*定义input标记样式 */
input {
  border-radius: 8px;
  width: 140px;
  height: 35px;
  border: 1px dashed #008000;
}
/*定义button,超链接标记样式 */
button,
.btn-success {
  border-radius: 8px;
  width: 80px;
  height: 35px;
  background: #008000;
  color: white;
}
/* 定义超链接样式 */
a {
  padding: 8px 10px;
}

.edit {
  background-color: #008000;
}
</style>
